#include "logmonitor.h"

#include <QStorageInfo>
#include <QDateTime>
#include <QDebug>
//test
#include <QtConcurrent>

#include "data/mycachedata.h"
#include "mylog.h"

void msgOut(QString name, QString val)
{
    qInfo() << name<<":" << val;
};

LogMonitor::LogMonitor(QObject *parent)
    : QThread(parent)
    , running(true)
{
    MyCacheData *ptr_MyCacheData = MyCacheData::getInstance();
    limitSize = ptr_MyCacheData->getFreeSizeLimit();
    logDir = AppLog::getLogDir();
    doTime = QDateTime::currentSecsSinceEpoch();
}

LogMonitor::~LogMonitor()
{
    running=false;
    try{
        this->terminate();
        this->wait();
        qInfo() << "LogMonitor::destroy\n";
    }catch(...){
        qDebug() << "LogMonitor::destroy fail\n";
    }
}

void LogMonitor::run()
{
    qInfo() << QString("LogMonitor start and run ");
    QStorageInfo storage(logDir);
    diskInfo(QString("rootPath"),storage.rootPath());
    if (storage.isReadOnly()){
        diskInfo(QString("isReadOnly"),QString("%1").arg(storage.isReadOnly()));
    }
    diskInfo(QString("name"),storage.name());
    diskInfo(QString("fileSystemType"),storage.fileSystemType());
    diskInfo(QString("size"),QString("%1MB").arg(storage.bytesTotal()/1000/1000));
    diskInfo(QString("availableSize"),QString("%1MB").arg(storage.bytesAvailable()/1000/1000));

//    qInfo() << "name:" << storage.name();
//    qInfo() << "fileSystemType:" << storage.fileSystemType();
//    qInfo() << "size:" << storage.bytesTotal()/1000/1000 << "MB";
//    qInfo() << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";

//    QDir logDir_(logDir);
//    QStringList filenameList = logDir_.entryList(QDir::Files,QDir::Time);
//    qInfo()<< filenameList;

    while (running) {
        if(doTime<QDateTime::currentSecsSinceEpoch()){
            doTime = QDateTime::currentSecsSinceEpoch()+10;
            int curFreeSize = storage.bytesAvailable()/1000/1000;
            if(curFreeSize < limitSize){
                freeLog();
            }
        }
        this->msleep(100);
    }
    exec();
}

void LogMonitor::diskInfo(QString name, QString val)
{
    //info out
    qInfo() << name<<":" << val;
//    //test
//    QFuture<void> fut1 = QtConcurrent::run(msgOut, name,val);
//    fut1.waitForFinished();
}

void LogMonitor::freeLog()
{
    QDir logDir_(logDir);
    QFileInfoList files = logDir_.entryInfoList(QDir::Files,QDir::Time);
    if(files.empty())
        return;
    QString oldFileName = (*files.crbegin()).absoluteFilePath();
    if(oldFileName.contains(QDate::currentDate().toString("yyyy-MM-dd")))
        return;
    if(!logDir_.remove(oldFileName))
    {
        qDebug() << QString("remove log file(%1) error").arg(oldFileName);
    }
}
